﻿using System;
using System.Reflection;
using Jayden.Dll.Core.Persistence.Attributes;

namespace Jayden.Dll.Core.Persistence.Models
{
	public class Property
	{
		private Entity m_Entity;
		private string m_Name;
		private PropertyInfo m_PropertyInfo;
		private Field m_Field;

		public Property(Entity entity, string name, Field field, PropertyInfo info)
		{
			m_Entity = entity;
			m_Name = name;
			m_Field = field;
			m_PropertyInfo = info;
		}

		public Entity Entity { get { return m_Entity; } }
		public string Name { get { return m_Name; } }
		public PropertyInfo PropertyInfo { get { return m_PropertyInfo; } }
		public Field Field { get { return m_Field; } }

		public string FullName { get { return string.Format("{0}.{1}", Entity.FullName, Name); } }
		public override string ToString() { return FullName; }

		public object GetValue(object obj) { return PropertyInfo.GetValue(obj, null); }
		public void SetValue(object obj, object value)
		{
			if (value != null && value.GetType() != PropertyInfo.PropertyType)
			{
				if (PropertyInfo.PropertyType.IsEnum)
					value = Enum.Parse(PropertyInfo.PropertyType, value.ToString());
				else if (PropertyInfo.PropertyType.IsGenericType && PropertyInfo.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
				{
					Type underType = Nullable.GetUnderlyingType(PropertyInfo.PropertyType);
					if(underType.IsEnum)
						value = Enum.Parse(underType, value.ToString());
					else
						value = Convert.ChangeType(value, underType);
				}
				else
					value = Convert.ChangeType(value, PropertyInfo.PropertyType);
			}
			PropertyInfo.SetValue(obj, value, null);
		}
	}
}
